//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.user;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.Globals;

import com.broadvision.portal.services.util.TransferBeanUtils;
import com.broadvision.portal.services.*;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.web.servlet.SessionVisitor;
import com.broadvision.visitor.exceptions.VisitorProfileException;
import com.broadvision.system.accesscontrol.client.*;
import com.broadvision.visitor.client.VisitorManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.data.common.IQualifierValue;
import com.broadvision.data.common.QualifierValueSetting;
import com.broadvision.data.cache.CacheManager;
import com.broadvision.data.cache.CacheNames;
import com.broadvision.data.cache.SequenceCacheHelper;
import com.broadvision.data.webcache.WebCacheManager;

import com.broadvision.data.common.DataConstants;
import com.broadvision.manage.common.tools.user.UserSearch;
import com.broadvision.manage.common.tools.user.UserProfile;
import com.broadvision.manage.tools.action.BaseAction;
import com.broadvision.license2.*;

/**
 * Provides the implementation of Action for saving a user's profile.
 */
public class ProfileSaveAction extends BaseAction {

  public static final String VIEW_BEAN_NAME = "mtUserEditView";
   private static final String VisitorIdsPerServiceSequence = "BV_VisitorIdsPerServiceSequence";

  /**
   * Implements the action for saving a user's profile.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
				      ActionForm form,
				      HttpServletRequest request,
				      HttpServletResponse response)
    throws Exception
  {
                                           
    try {    
      PortalVisitor agent = getPortalVisitor(request);
      Visitor visitor = agent.getVisitor();

      long profileId = UserProfile.UNDEFINED_USER_ID;
      String parameter = request.getParameter("userId");
      if (null != parameter && parameter.length() > 0) {
        profileId = Long.parseLong(parameter);
      }

      if (!UserProfile.isPermitted(visitor, "Save") && (profileId != visitor.getId()) && (!UserProfile.isOrganizationAdmin(visitor))) {
	  request.setAttribute(Globals.ERROR_KEY, "error.application");
	  return mapping.findForward("failure");
      }
      
      // taking care of checkbox
      String kmUserDeleted = (String) request.getParameter("kmUserDeleted");
      if (null == kmUserDeleted) {
	  UserUtils.setP(form, "kmUserDeleted", Boolean.FALSE);	
      }
      
      String epEmailAlert = (String) request.getParameter("epEmailAlert");
      if (null == epEmailAlert) {
	  UserUtils.setP(form, "epEmailAlert", Boolean.FALSE);	
      }
      UserProfile userProfile = new UserProfile();
      TransferBeanUtils.copyPropertiesToModel(userProfile, form);
      TransferBeanUtils.copyPropertiesToModel(userProfile.getDynaBean(), form);
      
      boolean existingUser = false;
      if (userProfile.getUserId() != UserProfile.UNDEFINED_USER_ID) {
	  existingUser = true;
      }

      boolean hasError = false;
      try {
	  // save the profile attributes first. there may be some errors
	  userProfile.setUpdateRole(false);
	   
	  userProfile.save(); 

	  PortalVisitor pUser = new PortalVisitor(userProfile.getVisitor().getId(), agent);
	 // update visitor list for services if needed
          if (!existingUser) {
	      try {
	          CacheManager cmgr = null;
                  if (WebCacheManager.exists())
	           cmgr = WebCacheManager.getWebCacheManager();

	            SequenceCacheHelper helper = new SequenceCacheHelper(
			CacheNames.DefaultSequenceCache, cmgr);
	            helper.updateSequence(VisitorIdsPerServiceSequence);
              } catch(Exception e) {
	      }
	  }
	  pUser.setServiceId(getServiceId(request));      

	  // save the user template
	  if (null != UserUtils.getP(form, "epUserTmplId")) {
	      long epUserTmplId = ((Long) UserUtils.getP(form, "epUserTmplId")).longValue();
	      if (-1 != epUserTmplId) {
	        // to see whether we need to clean out the qualifier in case there is a change of user template
                boolean replaceQvs = false;
                if (!existingUser) {
                  // new user
		  replaceQvs = true;
		}
		else {
                  try {
                    // the visitor may not be in the service
		    VisitorUserTemplate vUT = pUser.getVisitorUserTemplate();
		    if (null != vUT) {
                      UserTemplate ut = vUT.getUserTemplate();
                      if ((null != ut) && (ut.getId() != epUserTmplId)) {
                        replaceQvs = true;
		      }
		    }
		  }
		  catch (Exception ex) {
		  }
		}

		pUser.setUserTemplate(epUserTmplId);
		pUser.setEmailAlert(((Boolean) UserUtils.getP(form, "epEmailAlert")).booleanValue()); 

		if (replaceQvs) {
		  // template has been changed
		  // delete all qualifiers for this user and
		  // copy all the qualifiers and their values from the user template to the user

		  UserTemplate newUT = new UserTemplate(getServiceId(request), epUserTmplId, pUser);
		  List qVList = new ArrayList();
		  long[] qIds = newUT.getQualifierIds();
		  if (qIds != null) {
		    for (int n = 0; n < qIds.length; n++) {
		      long[] qVs = newUT.getQualifierValueIds(qIds[n]);
		      if (qVs != null) {
		        for (int m = 0; m < qVs.length; m++) {
			  qVList.add(new QualifierValueSetting(qIds[n], qVs[m]));
			}
		      }
		    }
		  }
		  pUser.replaceQualifierValues(qVList);
		}
	      }
	  }
      }
      catch (VisitorProfileException ex) {
	  //ex.printStackTrace();
	  if (existingUser) {
	      request.setAttribute(Globals.ERROR_KEY, "error.application");
	  }
	  else {
	      request.setAttribute(Globals.ERROR_KEY, "error.user.profile.save.new");
	  }
	  hasError = true;
      }
      
      request.setAttribute("userId", String.valueOf(userProfile.getUserId()));
      if (hasError) {
	  // need to forward back to the editing page
	  
	  //set data into view bean.
	  ViewDynaBean view = new ViewDynaBean(VIEW_BEAN_NAME, mapping);
	  request.setAttribute(VIEW_BEAN_NAME, view);
	  
	  UserUtils.setP(view, "useFullName", new Boolean(!VisitorManager.isUsingFMLName()));
	  
	  String formattedName = 
	      UserUtils.getFormattedName(userProfile.getVisitor(),
					 getResources(request), 
					 getLocale(request));
	  
	  UserUtils.setP(view, "formattedName", formattedName);

	  // grab the list of user templates: a temporary solution before the pop-up page is ready
	  List userTemplateList = UserTemplate.getUserTemplates (getServiceId(request),
								 DataConstants.BV_ONLINE_DB_CONTENT,
								 0,
								 getPortalVisitor(request));
	  
	  UserUtils.setP(view, "userTemplateList", userTemplateList);
	  
	  return mapping.findForward("error");
      }      
    }
    catch (Exception ex) {
	ex.printStackTrace();
	request.setAttribute(Globals.ERROR_KEY, "error.application");
	return mapping.findForward("failure");
    }

    return mapping.findForward("success");
  }
}
